<template>
  <t-card>
    <t-space direction="vertical" style="width: 100%">
      <t-form
        v-show="showSearch"
        ref="queryRef"
        :data="queryParams"
        layout="inline"
        label-align="top"
        reset-type="initial"
        label-width="calc(4em + 12px)"
      >
        <t-form-item label="用户名称" name="userName">
          <t-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="用户昵称" name="nickname">
          <t-input v-model="queryParams.nickname" placeholder="请输入用户昵称" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="个性签名" name="signature">
          <t-input v-model="queryParams.signature" placeholder="请输入个性签名" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="邮件地址" name="email">
          <t-input v-model="queryParams.email" placeholder="请输入邮件地址" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="手机号" name="phoneNumber">
          <t-input v-model="queryParams.phoneNumber" placeholder="请输入手机号" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="密码" name="password">
          <t-input v-model="queryParams.password" placeholder="请输入密码" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="密码盐" name="salt">
          <t-input v-model="queryParams.salt" placeholder="请输入密码盐" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="积分" name="points">
          <t-input v-model="queryParams.points" placeholder="请输入积分" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="最后登录时间" name="lastLoginTime">
          <t-date-picker v-model="queryParams.lastLoginTime" allow-input clearable placeholder="请选择最后登录时间" />
        </t-form-item>
        <t-form-item label="创建时间">
          <t-date-range-picker
            v-model="dateRangeCreateTime"
            style="width: 240px"
            allow-input
            clearable
            separator="-"
            :placeholder="['开始日期', '结束日期']"
          />
        </t-form-item>
        <t-form-item label-width="0px" >
          <t-space align="end" style="height: 64px">
          <t-button theme="primary" @click="handleQuery">
            <template #icon> <search-icon /></template>
            搜索
          </t-button>
          <t-button theme="default" @click="resetQuery">
            <template #icon> <refresh-icon /></template>
            重置
          </t-button>
          </t-space>
        </t-form-item>
      </t-form>

      <t-table
        v-model:column-controller-visible="columnControllerVisible"
        :loading="loading"
        hover
        row-key="id"
        :data="userList"
        :columns="columns"
        :selected-row-keys="ids"
        select-on-row-click
        :pagination="pagination"
        :column-controller="{
          hideTriggerButton: true,
        }"
        :sort="sort"
        show-sort-column-bg-color
        @sort-change="handleSortChange"
        @select-change="handleSelectionChange"
      >
        <template #topContent>
          <t-row>
            <t-col flex="auto">
              <t-button v-hasPermi="['wx:user:add']" theme="primary" @click="handleAdd">
                <template #icon> <add-icon /></template>
                新增
              </t-button>
              <t-button
                v-hasPermi="['wx:user:edit']"
                theme="default"
                variant="outline"
                :disabled="single"
                @click="handleUpdate()"
              >
                <template #icon> <edit-icon /> </template>
                修改
              </t-button>
              <t-button
                v-hasPermi="['wx:user:remove']"
                theme="danger"
                variant="outline"
                :disabled="multiple"
                @click="handleDelete()"
              >
                <template #icon> <delete-icon /> </template>
                删除
              </t-button>
              <t-button v-hasPermi="['wx:user:export']" theme="default" variant="outline" @click="handleExport">
                <template #icon> <download-icon /> </template>
                导出
              </t-button>
              <span class="selected-count">已选 {{ ids.length }} 项</span>
            </t-col>
            <t-col flex="none">
              <t-button theme="default" shape="square" variant="outline" @click="showSearch = !showSearch">
                <template #icon> <search-icon /> </template>
              </t-button>
              <t-button theme="default" variant="outline" @click="columnControllerVisible = true">
                <template #icon> <setting-icon /> </template>
                列配置
              </t-button>
            </t-col>
          </t-row>
        </template>
        <template #avatarImage="{ row }">
          <image-preview :src="row.avatarImage" :width="60" :height="60" />
        </template>
        <template #status="{ row }">
          <t-switch :value="row.status == 0 ? false : true" size="large" :label="renderContent" ></t-switch>
       </template>
        <template #operation="{ row }">
          <t-space :size="8" break-line>
            <t-link v-hasPermi="['wx:user:query']" theme="primary" hover="color" @click.stop="handleDetail(row)">
              <browse-icon />详情
            </t-link>
            <t-link v-hasPermi="['wx:user:edit']" theme="primary" hover="color" @click.stop="handleUpdate(row)">
              <edit-icon />修改
            </t-link>
            <t-link v-hasPermi="['wx:user:remove']" theme="danger" hover="color" @click.stop="handleDelete(row)">
              <delete-icon />删除
            </t-link>
          </t-space>
        </template>
      </t-table>
    </t-space>

    <!-- 添加或修改微信用户对话框 -->
    <t-dialog
      v-model:visible="open"
      :header="title"
      destroy-on-close
      :close-on-overlay-click="false"
      width="1100px"
      attach="body"
      :confirm-btn="{
        loading: buttonLoading,
      }"
      @confirm="onConfirm"
    >
      <t-loading :loading="buttonLoading" size="small">
        <t-form
          ref="userRef"
          label-align="right"
          :data="form"
          :rules="rules"
          label-width="calc(5em + 41px)"
          scroll-to-first-error="smooth"
          @submit="submitForm"
        >
          <t-form-item label="微信用户OpenID" name="openId">
            <t-textarea v-model="form.openId" placeholder="请输入微信用户OpenID" />
          </t-form-item>
          <t-form-item label="用户名称" name="userName">
            <t-textarea v-model="form.userName" placeholder="请输入用户名称" />
          </t-form-item>
          <t-form-item label="用户昵称" name="nickname">
            <t-textarea v-model="form.nickname" placeholder="请输入用户昵称" />
          </t-form-item>
          <t-form-item label="头像图片" name="avatarImage">
            <image-upload v-model="form.avatarImage" :limit="1" />
          </t-form-item>
          <t-form-item label="个性签名" name="signature">
            <t-textarea v-model="form.signature" placeholder="请输入个性签名" />
          </t-form-item>
          <t-form-item label="邮件地址" name="email">
            <t-textarea v-model="form.email" placeholder="请输入邮件地址" />
          </t-form-item>
          <t-form-item label="手机号" name="phoneNumber">
            <t-textarea v-model="form.phoneNumber" placeholder="请输入手机号" />
          </t-form-item>
          <t-form-item label="密码" name="password">
            <t-textarea v-model="form.password" placeholder="请输入密码" />
          </t-form-item>
          <t-form-item label="用户是否注册" name="status">
            <t-textarea v-model="form.salt" placeholder="请修改用户状态" />
          </t-form-item>
          <t-form-item label="积分" name="points">
            <t-input-number v-model="form.points" placeholder="请输入" />
          </t-form-item>
          <t-form-item label="最后登录时间" name="lastLoginTime">
            <t-date-picker
              v-model="form.lastLoginTime"
              enable-time-picker
              allow-input
              clearable
              placeholder="请选择最后登录时间"
            />
          </t-form-item>
        </t-form>
      </t-loading>
    </t-dialog>

    <!-- 微信用户详情 -->
    <t-dialog
      v-model:visible="openView"
      header="微信用户详情"
      placement="center"
      width="800px"
      attach="body"
      :footer="false"
    >
      <my-descriptions :loading="openViewLoading">
        <t-descriptions-item label="微信用户OpenID" :span="2">{{ form.openId }}</t-descriptions-item>
        <t-descriptions-item label="用户名称" :span="2">{{ form.userName }}</t-descriptions-item>
        <t-descriptions-item label="用户昵称" :span="2">{{ form.nickname }}</t-descriptions-item>
        <t-descriptions-item label="用户类型">{{ form.userType }}</t-descriptions-item>
        <t-descriptions-item label="">{{ form.sex }}</t-descriptions-item>
        <t-descriptions-item label="头像图片">
          <image-preview :src="form.avatarImage" :width="60" :height="60" />
        </t-descriptions-item>
        <t-descriptions-item label="个性签名" :span="2">{{ form.signature }}</t-descriptions-item>
        <t-descriptions-item label="邮件地址" :span="2">{{ form.email }}</t-descriptions-item>
        <t-descriptions-item label="手机号" :span="2">{{ form.phoneNumber }}</t-descriptions-item>
        <t-descriptions-item label="密码" :span="2">{{ form.password }}</t-descriptions-item>
        <t-descriptions-item label="密码盐" :span="2">{{ form.salt }}</t-descriptions-item>
        <t-descriptions-item label="积分">{{ form.points }}</t-descriptions-item>
        <t-descriptions-item label="用户是否注册">{{ form.status }}</t-descriptions-item>
        <t-descriptions-item label="最后登录时间">{{ parseTime(form.lastLoginTime) }}</t-descriptions-item>
        <t-descriptions-item label="创建时间">{{ parseTime(form.createTime) }}</t-descriptions-item>
      </my-descriptions>
    </t-dialog>
  </t-card>
</template>
<script lang="tsx" setup>
defineOptions({
  name: 'User',
});
import {
  AddIcon,
  BrowseIcon,
  DeleteIcon,
  DownloadIcon,
  EditIcon,
  RefreshIcon,
  SearchIcon,
  SettingIcon,
} from 'tdesign-icons-vue-next';
import type {
  FormInstanceFunctions,
  FormRule,
  PageInfo,
  PrimaryTableCol,
  SubmitContext,
  TableSort,
} from 'tdesign-vue-next';
import { computed, getCurrentInstance, ref } from 'vue';
import { ArrayOps } from '@/utils/array';

import type { WxUserForm, WxUserQuery, WxUserVo } from '@/api/wx/model/userModel';
import { listUser, getUser, delUser, addUser, updateUser } from '@/api/wx/user';
import { CloseIcon, CheckIcon } from 'tdesign-icons-vue-next';
// TODO开关switch
const renderContent = (h, data) => {
return data.value ? <CheckIcon /> : <CloseIcon />;
};
const { proxy } = getCurrentInstance();

const openView = ref(false);
const openViewLoading = ref(false);
const userRef = ref<FormInstanceFunctions>();
const open = ref(false);
const buttonLoading = ref(false);
const title = ref('');
const userList = ref<WxUserVo[]>([]);
const loading = ref(false);
const columnControllerVisible = ref(false);
const showSearch = ref(true);
const total = ref(0);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const sort = ref<TableSort>();
const dateRangeCreateTime = ref([]);

// 校验规则
const rules = ref<Record<string, Array<FormRule>>>({});

// 列显隐信息
const columns = ref<Array<PrimaryTableCol>>([
  { title: `选择列`, colKey: 'row-select', type: 'multiple', width: 50, align: 'center' },
  { title: `用户编号`, colKey: 'id', align: 'center', ellipsis: true },
  { title: `微信用户OpenID`, colKey: 'openId', align: 'center', ellipsis: true },
  { title: `用户名称`, colKey: 'userName', align: 'center', ellipsis: true },
  { title: `用户昵称`, colKey: 'nickname', align: 'center', ellipsis: true },
  { title: `用户类型`, colKey: 'userType', align: 'center' },
  { title: `性别`, colKey: 'sex', align: 'center' },
  { title: `头像图片`, colKey: 'avatarImage', align: 'center', width: 120 },
  { title: `个性签名`, colKey: 'signature', align: 'center', ellipsis: true },
  { title: `邮件地址`, colKey: 'email', align: 'center', ellipsis: true },
  { title: `手机号`, colKey: 'phoneNumber', align: 'center', ellipsis: true },
  { title: `密码盐`, colKey: 'salt', align: 'center', ellipsis: true },
  { title: `积分`, colKey: 'points', align: 'center' },
  { title: `用户是否注册`, colKey: 'status', align: 'center' },
  { title: `最后登录时间`, colKey: 'lastLoginTime', align: 'center', minWidth: 112, width: 120 },
  { title: `创建时间`, colKey: 'createTime', align: 'center', minWidth: 112, width: 120, sorter: true },
  { title: `操作`, colKey: 'operation', align: 'center', width: 120 },
]);
// 提交表单对象
const form = ref<WxUserVo & WxUserForm>({});
// 查询对象
const queryParams = ref<WxUserQuery>({
  pageNum: 1,
  pageSize: 10,
  userName: undefined,
  nickname: undefined,
  userType: undefined,
  sex: undefined,
  signature: undefined,
  email: undefined,
  phoneNumber: undefined,
  password: undefined,
  salt: undefined,
  points: undefined,
  status: undefined,
  lastLoginTime: undefined,
});
// 分页
const pagination = computed(() => {
  return {
    current: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    total: total.value,
    showJumper: true,
    onChange: (pageInfo: PageInfo) => {
      queryParams.value.pageNum = pageInfo.current;
      queryParams.value.pageSize = pageInfo.pageSize;
      getList();
    },
  };
});

/** 查询微信用户列表 */
function getList() {
  loading.value = true;
  proxy.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime');
  listUser(queryParams.value)
    .then((response) => {
      console.log("response.rows",response.rows)
      userList.value = response.rows;
      total.value = response.total;
    })
    .finally(() => (loading.value = false));
}

// 表单重置
function reset() {
  form.value = {};
  proxy.resetForm('userRef');
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRangeCreateTime.value = [];
  proxy.resetForm('queryRef');
  queryParams.value.pageNum = 1;
  handleSortChange(null);
}

/** 排序触发事件 */
function handleSortChange(value?: TableSort) {
  sort.value = value;
  if (Array.isArray(value)) {
    queryParams.value.orderByColumn = value.map((item) => item.sortBy).join(',');
    queryParams.value.isAsc = value.map((item) => (item.descending ? 'descending' : 'ascending')).join(',');
  } else {
    queryParams.value.orderByColumn = value?.sortBy;
    queryParams.value.isAsc = value?.descending ? 'descending' : 'ascending';
  }
  getList();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: Array<string | number>) {
  ids.value = selection;
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加微信用户';
}

/** 详情按钮操作 */
function handleDetail(row: WxUserVo) {
  reset();
  openView.value = true;
  openViewLoading.value = true;
  const id = row.id;
  getUser(id).then((response) => {
    form.value = response.data;
    openViewLoading.value = false;
  });
}

/** 修改按钮操作 */
function handleUpdate(row?: WxUserVo) {
  buttonLoading.value = true;
  reset();
  open.value = true;
  title.value = '修改微信用户';
  const id = row?.id || ids.value.at(0);
  getUser(id).then((response) => {
    buttonLoading.value = false;
    form.value = response.data;
  });
}

/** 提交按钮 */
function onConfirm() {
  userRef.value.submit();
}

/** 提交表单 */
function submitForm({ validateResult, firstError }: SubmitContext) {
  if (validateResult === true) {
    buttonLoading.value = true;
    const msgLoading = proxy.$modal.msgLoading('提交中...');
    if (form.value.id) {
      updateUser(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    } else {
      addUser(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    }
  } else {
    proxy.$modal.msgError(firstError);
  }
}

/** 删除按钮操作 */
function handleDelete(row?: WxUserVo) {
  const $ids = row?.id || ids.value;
  proxy.$modal.confirm(`是否确认删除微信用户编号为${$ids}的数据项？`, () => {
    const msgLoading = proxy.$modal.msgLoading('正在删除中...');
    return delUser($ids)
      .then(() => {
        ids.value = ArrayOps.fastDeleteElement(ids.value, $ids);
        getList();
        proxy.$modal.msgSuccess('删除成功');
      })
      .finally(() => {
        proxy.$modal.msgClose(msgLoading);
      });
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime');
  proxy.download(
    'wx/user/export',
    {
      ...queryParams.value,
    },
    `user_${new Date().getTime()}.xlsx`,
  );
}

getList();
</script>
